package com.huluobo.lib_base

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File

/**
 *  Created by LC on 2025/4/11.
 */
object DownloadUtils {
    fun download(url: String, file: File): Flow<UIState> {
        return flow {
            val request = Request.Builder().url(url).get().build()
            val response = OkHttpClient.Builder().build().newCall(request).execute()
            if (response.isSuccessful) {
                response.body.let { body ->
                    file.outputStream().let { os ->
                        val bs = body?.byteStream()
                        var len = 0
                        val byteArray = ByteArray(DEFAULT_BUFFER_SIZE)
                        while (bs?.read(byteArray).also { len = it!! } != -1) {
                            os.write(byteArray, 0, len)
                        }
                        os.flush()
                        os.close()
                        emit(UIState.OnSuccess("下载成功", type = HttpType.DOWNLOAD))
                    }
                }
            } else {
                emit(UIState.OnError("下载失败"))
            }
        }
    }
}